 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=22 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:53 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Fields should usually be private
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='final,get,pitfall,set,field,private,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Fields should usually be private</div>

<div class='main-body'>
 
<br>Fields should be declared <tt>private</tt> unless there is a good 
reason for <em>not</em> doing so. 

<P>One of the guiding principles of lasting value in programming is 
"<a href='TopicAction23a3-2.html'>Minimize ripple effects</a> by keeping secrets." When a field is 
<tt>private</tt>, the caller <b>cannot usually</b> get <em>inappropriate direct access</em> to the field. 

<P>To clarify, there are three possibilities for a <tt>private</tt> field :
<ul>
<li>primitive data such as <tt>int</tt>, <tt>boolean</tt>, and so on. 
<li><a href='TopicActiond838-2.html'>immutable objects</a> such as <tt>String</tt> and <tt>BigDecimal</tt>, whose 
data never changes.
<li>mutable objects, whose data can change (that is, they can change <em>state</em>). These 
need special care, and often need a <a href='TopicAction79f1-2.html'>defensive copy</a>. It is easy 
to forget this. <span class='highlight'>You should always remember that mutable object fields are 'hot spots' 
in your code, and need special care.</span>
</ul>

<P>It is only the last case - the mutable object <tt>private</tt> field  - where 
<em>inappropriate direct access</em> to a <tt>private</tt> field is possible. 
Here is an illustration :

<p><b>Example 1</b>
<br>
<PRE>

<span class='keyword'>import</span> java.util.Date;

<span class='comment'>/**
* Planet is an immutable class, since there is no way to change
* its state after construction.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Planet {

  <span class='keyword'>public</span> Planet (<span class='keyword'>double</span> aMass, String aName, Date aDateOfDiscovery) {
     fMass = aMass;
     fName = aName;
     <span class='comment'>//make a private copy of aDateOfDiscovery
</span>     <span class='comment'>//this is the only way to keep the fDateOfDiscovery
</span>     <span class='comment'>//field private, and shields this class from any changes that 
</span>     <span class='comment'>//the caller may make to the original aDateOfDiscovery object
</span>     fDateOfDiscovery = <span class='keyword'>new</span> Date(aDateOfDiscovery.getTime());
  }

  <span class='comment'>/**
  * Returns a primitive value.
  *
  * The caller can do whatever they want with the return value, without 
  * affecting the internals of this class. Why? Because this is a primitive 
  * value. The caller sees its "own" double that simply has the
  * same value as fMass.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>double</span> getMass() {
    <span class='keyword'>return</span> fMass;
  }

  <span class='comment'>/**
  * Returns an immutable object.
  *
  * The caller gets a direct reference to the internal field. But this is not 
  * dangerous, since String is immutable and cannot be changed.
  */</span>
  <span class='keyword'>public</span> String getName() {
    <span class='keyword'>return</span> fName;
  }

<span class='comment'>//  /**
</span><span class='comment'>//  * Returns a mutable object - likely bad style.
</span><span class='comment'>//  *
</span><span class='comment'>//  * The caller gets a direct reference to the internal field. This is usually dangerous, 
</span><span class='comment'>//  * since the Date object state can be changed both by this class and its caller.
</span><span class='comment'>//  * That is, this class is no longer in complete control of fDate.
</span><span class='comment'>//  */
</span><span class='comment'>//  public Date getDateOfDiscovery() {
</span><span class='comment'>//    return fDateOfDiscovery;
</span><span class='comment'>//  }
</span>
  <span class='comment'>/**
  * Returns a mutable object - good style.
  * 
  * Returns a defensive copy of the field.
  * The caller of this method can do anything they want with the
  * returned Date object, without affecting the internals of this
  * class in any way. Why? Because they do not have a reference to 
  * fDate. Rather, they are playing with a second Date that initially has the 
  * same data as fDate.
  */</span>
  <span class='keyword'>public</span> Date getDateOfDiscovery() {
    <span class='keyword'>return</span> <span class='keyword'>new</span> Date(fDateOfDiscovery.getTime());
  }

  <span class='comment'>// PRIVATE //
</span>
  <span class='comment'>/**
  * Final primitive data is always immutable.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> <span class='keyword'>double</span> fMass;

  <span class='comment'>/**
  * An immutable object field. (String objects never change state.)
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> String fName;

  <span class='comment'>/**
  * A mutable object field. In this case, the state of this mutable field
  * is to be changed only by this class. (In other cases, it makes perfect
  * sense to allow the state of a field to be changed outside the native
  * class; this is the case when a field acts as a "pointer" to an object
  * created elsewhere.)
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> Date fDateOfDiscovery;
}
 
</PRE>
<br>
<br><b>Example 2</b>

<p>This is a counter-example.

<p>A common exception to this rule is that primitive constants and <i>immutable</i>
objects can be declared as <tt>public static final</tt> fields. For example, see
<a href='TopicAction03b1-2.html'>class for constants</a>.
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction79f1-2.html?Id=15'>Defensive copying</a> <br>
 
  
  <a href='TopicActiond838-2.html?Id=29'>Immutable objects</a> <br>
 
  
  <a href='TopicAction23a3-2.html?Id=123'>Minimize ripple effects</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='22'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=22 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:53 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
